﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Text;
using System.Net;

namespace com.googlecode.jenkins.helpers
{
    public class HttpHelper
    {
        
        private static String ComputeParameters(Dictionary<String, String> parameters)
        {
            var p = new List<string>();
            foreach (var parameter in parameters)
            {
                p.Add(parameter.Key + "=" + parameter.Value);
            }
            return String.Join("&", p.ToArray());
        }

        public static HttpWebResponse Post(String url, Dictionary<String, String> parameters)
        {
            var webReq = (HttpWebRequest)WebRequest.Create(url);
            var buffer = Encoding.ASCII.GetBytes(ComputeParameters(parameters));
            webReq.Method = "POST";
            webReq.ContentType = "application/x-www-form-urlencoded";
            webReq.ContentLength = buffer.Length;
            var postData = webReq.GetRequestStream();
            postData.Write(buffer, 0, buffer.Length);
            postData.Close();
            return (HttpWebResponse)webReq.GetResponse();
            
        }

        public static HttpWebResponse Get(string url)
        {
            var webReq = (HttpWebRequest)WebRequest.Create(url);
            webReq.Method = "GET";
            return (HttpWebResponse)webReq.GetResponse();
        }


        public static HttpWebResponse Post(string url, Stream configFile, string contentType)
        {
            var webReq = (HttpWebRequest)WebRequest.Create(url);
            var buffer = StreamHelper.ReadFully(configFile);
            webReq.Method = "POST";
            webReq.ContentType = contentType;
            webReq.ContentLength = buffer.Length;
            var postData = webReq.GetRequestStream();
            postData.Write(buffer, 0, buffer.Length);
            postData.Close();
            return (HttpWebResponse)webReq.GetResponse();
        }

        public static HttpWebResponse Post(string url)
        {
            var webReq = (HttpWebRequest)WebRequest.Create(url);
            webReq.Method = "POST";
            return (HttpWebResponse)webReq.GetResponse();
        }
    }
}
